{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Object detection based on  Deep Learning.ipynb",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OaEGVW0XCzhL",
        "colab_type": "text"
      },
      "source": [
        "#**Object Detection based on Deep Learning**\n",
        "\n",
        "![DL](https://i.ibb.co/GVbs5bV/fig.png)\n",
        "\n",
        "##What is object detection?\n",
        "In recent years, object detection in images has been greatly improved through numerous implementations of the Deep Learning paradigm. Creating trainable models helps to rapidly detect and classify discriminating features without having to develop a sophisticated algorithm. In fact, detecting objects and locating them in an image is an increasingly vital aspect of computer vision research. This discipline seeks out instances, their class labels and their positions in the visual data. This domain stands at the overlap of two other fields: image classification and object localization. Indeed, object detection is based on the following principle: for a specific image, we look for regions of the image that might contain an object and then, for each of these detected regions, we extract and classify it using an image classification model. Those regions of the initial image showing good classification results are maintained and the remainder is discarded. Thus, for a good object detection method, it is necessary to have a robust region detection algorithm as well as a good image classification model.\n",
        "\n",
        "The following projects and tutorials related to the video detection task are provided for further details:\n",
        "\n",
        "\n",
        "\n",
        "*    [Object detection project for real-time (webcam) and offline (video processing) application.](https://github.com/lbeaucourt/Object-detection)\n",
        "\n",
        "*   [Object-detection: Single Shot MultiBox Detector(SSD) in TensorFlow.](https://github.com/hjptriplebee/SSD_tensorflow)\n",
        "\n",
        "* [Darknet](https://github.com/rlan/darknet)\n",
        "\n",
        "* [PyTorch implementation of RetinaNet with the goal to reproduce results in the \"focal loss for dense object detection\" paper.](https://github.com/cedrickchee/pytorch-RetinaNet)\n",
        "\n",
        "* [Robosapien object detector using Darkflow](https://github.com/ogbanugot/Robosapien-Object-Detector-using-Darkflow)\n",
        "\n",
        "* [Object Detection Application](https://github.com/siddartha19/Object-Detection-Application)\n",
        "* [Understanding Object Detection](https://towardsdatascience.com/understanding-object-detection-9ba089154df8)\n",
        "\n",
        "The following are some useful books that will help you learn the different aspects of object detection:\n",
        "\n",
        "\n",
        "\n",
        "1.   [Advanced Applied Deep Learning](https://aax-us-east.amazon-adsystem.com/x/c/Qja79-QaoJHEO-MVQ1oDZwsAAAFwtKQVSwEAAAFKAQDMYqQ/https://assoc-redirect.amazon.com/g/r/https://www.amazon.com/Advanced-Applied-Deep-Learning-Convolutional/dp/1484249755?creativeASIN=1484249755&linkCode=w61&imprToken=bnWxJoN9ehtfoAkba-1ChA&slotNum=3&tag=uuid10-20)\n",
        "2.   [Object Detection in Low-spatial-resolution Aerial Imagery Using Convolutional Neural Networks](https://aax-us-east.amazon-adsystem.com/x/c/Qja79-QaoJHEO-MVQ1oDZwsAAAFwtKQVSwEAAAFKAQDMYqQ/https://assoc-redirect.amazon.com/g/r/https://www.amazon.com/Detection-Low-spatial-resolution-Imagery-Convolutional-Networks/dp/1688093427?creativeASIN=1688093427&linkCode=w61&imprToken=bnWxJoN9ehtfoAkba-1ChA&slotNum=9&tag=uuid10-20)\n",
        "3. [Hierarchical approach for object detection using shape descriptors](https://aax-us-east.amazon-adsystem.com/x/c/Qja79-QaoJHEO-MVQ1oDZwsAAAFwtKQVSwEAAAFKAQDMYqQ/https://assoc-redirect.amazon.com/g/r/https://www.amazon.com/Hierarchical-approach-object-detection-descriptors/dp/3330353066?creativeASIN=3330353066&linkCode=w61&imprToken=bnWxJoN9ehtfoAkba-1ChA&slotNum=15&tag=uuid10-20)\n",
        "4. [Application of Deep Learning in Object Detection\n",
        "Application of Deep Learning in Object Detection using Tensorflow](https://aax-us-east.amazon-adsystem.com/x/c/Qja79-QaoJHEO-MVQ1oDZwsAAAFwtKQVSwEAAAFKAQDMYqQ/https://assoc-redirect.amazon.com/g/r/https://www.amazon.com/Application-Deep-Learning-Object-Detection/dp/613945705X?creativeASIN=613945705X&linkCode=w61&imprToken=bnWxJoN9ehtfoAkba-1ChA&slotNum=21&tag=uuid10-20)\n",
        "\n",
        "###**Object localization v.s. object classification**\n",
        "Object detection consists of identifying and locating one or several objects in the image. Depending on a given input, a detector will return information of two dimensions: the class labels and location of each instance. Locating an object in an image is complex and measuring the localization performance needs an adapted metric. Moreover, unlike classification, several targets can be located in the same image and the detector must be able to accurately locate them. For a single input, an object detector returns the detected objects in the image and their associated bounding boxes. Some strategies are available to address this challenge. The first one(see Figure 1), based on object recognition approaches, essentially consists of simply predicting the size of a bounding box and the class to which it belongs. The second approach (see Figure 2), probably the best known, is the proposed region approach where another model extracts a reduced number of candidate frames (i.e. proposals) that contain an object and the problem is then simplified into a recognition problem.\n",
        "\n",
        "**Figure 1:** Object detection based on a single-stage method ![Fig1](https://i.ibb.co/fCjNBpw/1.png)\n",
        "\n",
        "**Figure 2:** Object detection based on a two-stages method (region proposals) ![Fig2](https://i.ibb.co/1MkgbS4/2.png)\n",
        "\n",
        "###**Contour-based object detection**\n",
        "\n",
        "cIn this section, we will discuss different methods of contour detection and compare them with each other.\n",
        "\n",
        "**1. SOBEL detector**\n",
        "\n",
        "The Sobel detector is one of the methods we're looking at right now. Like most detectors, this one is based on calculating the gradients of the image at each point. Sobel's discrete method is based on multiplying the intensity matrix around the desired pixel by the following matrices, representing the \" mixture \" between filters derived according to x and y, and Gaussian filters that add importance to the nearest pixels.\n",
        "\n",
        "![Sobel](https://i.ibb.co/6cQx0b0/3.png)\n",
        "\n",
        "**2. LAPLACIAN detector**\n",
        "\n",
        "An alternative method that has been explored is the use of the Laplacian. The principle is quite similar and is based on the second derivative of the intensity. Discretely, the Laplacian matrix is implemented by the product of the intensity matrices of the pixel contour with the following matrices :\n",
        "\n",
        "[0 1 0]\n",
        "\n",
        "[1 -4 1]\n",
        "\n",
        "[0 1 0]\n",
        "\n",
        "![Lap](https://i.ibb.co/M7L0nbr/4.png)\n",
        "\n",
        "**3. CANNY detector**\n",
        "\n",
        "The Canny method uses a Gaussian filter and then derivation matrices along both axes to determine the magnitude and angle of the gradient. Finally, a hysteresis is applied to smooth out the most important edges.\n",
        "\n",
        "\n",
        "![Canny](https://i.ibb.co/3C8xHxX/5.png)\n",
        "\n",
        "**4. PREWITT detector**\n",
        "\n",
        "This detector is pretty close to Sobel's. Concretely, it operates on the principle of gradient detection along the two major axes, in combination with an averaging filter.  \n",
        "\n",
        "\n",
        "![prewitt](https://i.ibb.co/XZLpZCk/6.png)\n",
        "\n",
        "\n",
        "###**Conventional methods for object detection: A use case**\n",
        "\n",
        "The objective of this use case is to develop and program algorithms to detect faces in images. To do this, one approach using [Viola-Jones' algorithm](https://www.cs.cmu.edu/~efros/courses/LBMV07/Papers/viola-cvpr-01.pdf) will be tested.\n",
        "The Viola-Jones technique (Haar Cascade Face Detector) is a method of detecting objects in images proposed by Paul Viola and Michael Jones in 2001 and widely used for face detection. This method detects objects by learning a classifier.\n",
        "\n",
        "The implementation of this detector is as follows:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MQGRq7uGmv-F",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "class HaarCascadeFaceDetector(AbstractSkinDetector):\n",
        "    \"\"\"\n",
        "    Face detector with the Viola Jones method\n",
        "    \"\"\"\n",
        "    METHOD_NAME = \"viola_jones\"\n",
        "\n",
        "    def process(self):\n",
        "        # greyscale image for haar cascades\n",
        "        self.original = self.original.switch_color_space(\"GRAY\")\n",
        "        cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n",
        "\n",
        "        # face detections\n",
        "        faces = cascade.detectMultiScale(self.original.img, scaleFactor=1.1,\n",
        "                                         minNeighbors=5, minSize=(30, 30),\n",
        "                                         flags = cv2.cv.CV_HAAR_SCALE_IMAGE)\n",
        "\n",
        "        if DEBUG:\n",
        "            print(\"%s faces detected\" % len(faces))\n",
        "\n",
        "        # Bounding boxes are drawn around the faces on the resulting image.\n",
        "        for (x, y, w, h) in faces:\n",
        "            cv2.rectangle(self.result.img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n",
        "        self.result.save()\n",
        "\n",
        "\n",
        "def run_haar_cascade():\n",
        "    \"\"\"\n",
        "    Detects faces via haar cascades in all images.\n",
        "    \"\"\"\n",
        "    for img_name in chain(train_dataset(), test_dataset()):\n",
        "        _ = HaarCascadeFaceDetector(img_name)\n",
        "\n",
        "\n",
        "def benchmark(Detector, extra_args, use_test_data=True):\n",
        "    \"\"\"\n",
        "    Run a benchmark of the detector passed in arg\n",
        "        \"\"\"\n",
        "    print(\"Benchmark started for %s(%s)\" % (Detector.__name__, extra_args))\n",
        "\n",
        "    true_positive_rates = []\n",
        "    false_positive_rates = []\n",
        "\n",
        "    for image_name in (test_dataset() if use_test_data else train_dataset()):\n",
        "        detector = Detector(\n",
        "            image_name, *extra_args) if extra_args else Detector(image_name)\n",
        "        true_positive_rate, false_positive_rate = detector.rates()\n",
        "        true_positive_rates.append(true_positive_rate)\n",
        "        false_positive_rates.append(false_positive_rate)\n",
        "\n",
        "    # tp: true positive / fp: false positive\n",
        "    # avg: average     / std: standard deviation\n",
        "    tp_avg = np.mean(true_positive_rates)\n",
        "    tp_std = np.std(true_positive_rates)\n",
        "    fp_avg = np.mean(false_positive_rates)\n",
        "    fp_std = np.std(false_positive_rates)\n",
        "\n",
        "    print(\"Benchmark finished for %s(%s)\" % (Detector.__name__, extra_args))\n",
        "\n",
        "    return tp_avg, tp_std, fp_avg, fp_std\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AXk0eyIno4Xm",
        "colab_type": "text"
      },
      "source": [
        "The method is implemented with Opencv's haar cascade. We tested a few different parameters for this detector. Finally, we get an optimal result (see Figure) with a slight scaling of the image (10%), a minimum detection size of 30 pixels by 30 pixels and a minimum number of neighbors for the detection to be valid of 5.\n",
        "\n",
        "![res](https://i.ibb.co/R3PhwjP/8.png)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cqThgDJGmu6P",
        "colab_type": "text"
      },
      "source": [
        "###**Deep CNN -based object detection**\n",
        "\n",
        "Convolutional neural networks (CNN) are particular deep neural network (DNN) structures since the basic operation has become a convolution rather than a matrix multiplication. These networks have been developed to take advantage of big data with a structure (spatial, temporal, ...) such as images, videos, etc. As shown in Figure 3, their functioning is straightforward and requires some convolution operations.  The output is obtained by convolving the input image by a fixed number of kernels. The output of a kernel is obtained by multiplying the current position of a sliding window (i.e. receptive field) applied to the image. Besides, pooling or subsampling layers are added to the basic operations. They allow to reduce the spatial size of the representation in this way, they allow controlling overfitting problems. \n",
        "\n",
        "**Figure 3:** A basic structure of CNN![CNN](https://miro.medium.com/max/1000/1*zNs_mYOAgHpt3WxbYa7fnw.png)\n",
        "\n",
        "\n",
        "\n",
        "###**Use case 2:** CNN-based generic object detector\n",
        "\n",
        "**Deep Learning Framework:** [Pytorch](https://pytorch.org/) (An open source machine learning framework that accelerates the path from research prototyping to production deployment). Please follow the installation instructions on the framework's official [website](https://pytorch.org/).\n",
        "\n",
        "\n",
        "\n",
        "**Architecture:** The CNN model consists of three convolutional layers and two fully connected layers. Each convolutional layer uses a kernel of size 5 with a stride of 1 and rectified linear units, ReLU, are used as the activation function. After each of the first two convolutional layers, a max-pooling layer of size 2 with a stride of 2 is used. The network was trained over 50 epochs using the stochastic gradient descent (SGD) optimizer. For the first 30 epochs, the learning rate is set to 0.0001 and then it is updated to 0.00001. \n",
        "\n",
        "The CNN implementation is as follows:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WiBuD8NtgZTW",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import torch.nn as nn\n",
        "import torch.nn.functional as f\n",
        "class cnn_model(nn.Module):\n",
        "\n",
        "    def __init__(self):\n",
        "\n",
        "        super(cnn_model, self).__init__()\n",
        "\n",
        "        self.conv1 = nn.Conv2d(\n",
        "            in_channels=1,\n",
        "            out_channels=32,\n",
        "            kernel_size=5,\n",
        "            stride=1,\n",
        "            padding=0\n",
        "        )\n",
        "\n",
        "        self.conv2 = nn.Conv2d(\n",
        "            in_channels=32,\n",
        "            out_channels=64,\n",
        "            kernel_size=5,\n",
        "            stride=1,\n",
        "            padding=0\n",
        "        )\n",
        "\n",
        "        self.conv3 = nn.Conv2d(\n",
        "            in_channels=64,\n",
        "            out_channels=128,\n",
        "            kernel_size=5,\n",
        "            stride=1,\n",
        "            padding=0\n",
        "        )\n",
        "\n",
        "\n",
        "        self.fc1 = nn.Linear(\n",
        "            in_features=18*18*128,\n",
        "            out_features=2046\n",
        "        )\n",
        "\n",
        "        self.fc2 = nn.Linear(\n",
        "            in_features=2046,\n",
        "            out_features=4\n",
        "        )\n",
        "\n",
        "    def forward(self, val):\n",
        "        val = f.relu(self.conv1(val))\n",
        "        val = f.max_pool2d(val, kernel_size=2, stride=2)\n",
        "        val = f.relu(self.conv2(val))\n",
        "        val = f.max_pool2d(val, kernel_size=2, stride=2)\n",
        "        val = f.relu(self.conv3(val))\n",
        "        val = val.view(-1, 18*18*128)\n",
        "        val = f.dropout(f.relu(self.fc1(val)), p=0.5, training=self.training)\n",
        "        val = self.fc2(val)\n",
        "\n",
        "        return val"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vXGZsTKNhVku",
        "colab_type": "text"
      },
      "source": [
        "Source code to learn the model:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vM_g3_yyhvvX",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.optim as optim\n",
        "from torch.utils.data import DataLoader\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from functions import overlapScore\n",
        "\n",
        "\n",
        "from cnn_model import *\n",
        "from training_dataset import *\n",
        "\n",
        "def train_model(net, dataloader, batchSize, lr, momentum):\n",
        "    criterion = nn.MSELoss()\n",
        "    optimization = optim.SGD(net.parameters(), lr=lr, momentum=momentum)\n",
        "    scheduler = optim.lr_scheduler.StepLR(optimization, step_size=30, gamma=0.1)\n",
        "\n",
        "    for epoch in range(50):\n",
        "\n",
        "        scheduler.step()\n",
        "\n",
        "        for i, data in enumerate(dataloader):\n",
        "            optimization.zero_grad()\n",
        "\n",
        "            inputs, labels = data\n",
        "\n",
        "            inputs, labels = inputs.view(batchSize,1, 100, 100), labels.view(batchSize, 4)\n",
        "\n",
        "            outputs = net(inputs)\n",
        "\n",
        "            loss = criterion(outputs, labels)\n",
        "            loss.backward()\n",
        "            optimization.step()\n",
        "\n",
        "            pbox = outputs.detach().numpy()\n",
        "            gbox = labels.detach().numpy()\n",
        "            score, _ = overlapScore(pbox, gbox)\n",
        "\n",
        "            print('[epoch %5d, step: %d, loss: %f, Average Score = %f' % (epoch+1, i+1, loss.item(), score/batchSize))\n",
        "\n",
        "    print('Finish Training')\n",
        "\n",
        "\n",
        "if __name__ == '__main__':\n",
        "    # Hyper parameters\n",
        "    learning_rate = 0.0001\n",
        "    momentum = 0.9\n",
        "    batch = 100\n",
        "    no_of_workers = 2\n",
        "    shuffle = True\n",
        "\n",
        "\n",
        "    trainingdataset = training_dataset()\n",
        "    dataLoader = DataLoader(\n",
        "        dataset=trainingdataset,\n",
        "        batch_size=batch,\n",
        "        shuffle=shuffle,\n",
        "        num_workers=no_of_workers\n",
        "    )\n",
        "\n",
        "    model = cnn_model()\n",
        "    model.train()\n",
        "\n",
        "    train_model(model, dataLoader, batch,learning_rate, momentum)\n",
        "    torch.save(model.state_dict(), './trained_CNN_model.pth')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "02KjSj_7iFF6",
        "colab_type": "text"
      },
      "source": [
        "Source code for handling the dataset (reading data samples):"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UtzZlSuEictH",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import torch\n",
        "from torch.utils.data import Dataset, DataLoader\n",
        "\n",
        "class training_dataset(Dataset):\n",
        "    def __init__(self):\n",
        "      # Training set and corresponding ground truth images\n",
        "        trainX = np.asarray(pd.read_csv('./my_dataset/trainingData.csv', sep=',', header=None))\n",
        "        trainY = np.asarray(pd.read_csv('./my_dataset/ground-truth.csv', sep=',', header=None))\n",
        "        self.features_train = torch.Tensor(trainX)\n",
        "        self.groundTruth_train = torch.Tensor(trainY)\n",
        "\n",
        "        self.len = len(trainX)\n",
        "\n",
        "\n",
        "    def __getitem__(self, item):\n",
        "        return self.features_train[item], self.groundTruth_train[item]\n",
        "\n",
        "    def __len__(self):\n",
        "        return self.len"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rK5S_NLIjn9Y",
        "colab_type": "text"
      },
      "source": [
        "The following pseudo-code entails a function to calculate the overlap rate taking into account the ground truth boxes and the predicted bounding boxes."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YWM0OdPHjpDl",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "\n",
        "def overlap(rect1, rect2):\n",
        "\n",
        "    avgScore = 0\n",
        "    scores = []\n",
        "\n",
        "    for i, _ in enumerate(rects1):\n",
        "\n",
        "        rect1 = rect1[i]\n",
        "        rect2 = rect2[i]\n",
        "\n",
        "        left = np.max((rect1[0], rect2[0]))\n",
        "        right = np.min((rect1[0]+rect1[2], rect2[0]+rect2[2]))\n",
        "\n",
        "        top = np.max((rect1[1], rect2[1]))\n",
        "        bottom = np.min((rect1[1]+rect1[3], rect2[1]+rect2[3]))\n",
        "\n",
        "        # area of intersection\n",
        "        i = np.max((0, right-left))*np.max((0,bottom-top))\n",
        "\n",
        "        # combined area of two rectangles\n",
        "        u = rect1[2]*rect1[3] + rect2[2]*rect2[3] - i\n",
        "\n",
        "        # return the overlap ratio\n",
        "        # value is always between 0 and 1\n",
        "        score = np.clip(i/u, 0, 1)\n",
        "        avgScore += score\n",
        "        scores.append(score)\n",
        "\n",
        "    return avgScore, scores"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AyocdnccwjuL",
        "colab_type": "text"
      },
      "source": [
        "###**Real-time object detection and segmentation with Tensorflow**\n",
        "The objective of this use case is to explain the real-time object detection and segmentation by an example. To do this, we will develop a real-time segmentation application with a simple webcam. We will use the [Tensorflow framework](https://www.tensorflow.org/), the Mask RCNN network learned with the COCO dataset; which allows us to detect up to 100 different types of objects.\n",
        "\n",
        " First of all, let's make a list of our tools and libraries to install.\n",
        " \n",
        "* Linux Ubuntu \n",
        "* Python\n",
        "* Tensorflow\n",
        "* Open CV\n",
        "\n",
        "In order to check if your computer is ready, open a python3 console in the terminal by typing python3. Do the following imports:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hsXW3Y8iyKGa",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import cv2\n",
        "import numpy as np\n",
        "import tensorflow as tf\n",
        "from object_detection.utils import label_map_util\n",
        "from object_detection.utils import ops as utils_ops\n",
        "from object_detection.utils import visualization_utils as vis_util"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ajRj5Dbfyecu",
        "colab_type": "text"
      },
      "source": [
        "To make the model work, you need to load the network and its weights. You will find a list of all object detection models available with Tensorflow on this zoo model. For this tutorial, download mask_rcnn_resnet101_atrous_coco."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ek6qk08Pyffo",
        "colab_type": "text"
      },
      "source": [
        "We start with the last point: initialize the webcam. This allows two things: (1) to create the video stream and (2) to get the width and height of a frame of the stream in order to configure the output tensor of the mask.\n",
        " "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "7w99Egz4yrvA",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Init the video stream (with the first plugged webcam)\n",
        "cap = cv2.VideoCapture(0)\n",
        "if cap.isOpened():\n",
        "  # get vcap property\n",
        "  global_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n",
        "  global_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nY1oa5fMyvfL",
        "colab_type": "text"
      },
      "source": [
        "The next step is to import the label_map file. It is done using methods delivered with Tensorflow's object_detection."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NV2FQ3uQy3WW",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "label_map = label_map_util.load_labelmap(\"PATH/TO/LABELS\")\n",
        "categories = label_map_util.convert_label_map_to_categories(\n",
        "  label_map, \n",
        "  max_num_classes=NUM_CLASSES,\n",
        "  use_display_name=True)\n",
        "category_index = label_map_util.create_category_index(categories)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RQ7xygEdy_Ap",
        "colab_type": "text"
      },
      "source": [
        "We then proceed with the import of the model and the collection of the tensors.\n",
        " "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dfTxujJjzGK1",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Init TF Graph and get all needed tensors\n",
        "detection_graph = tf.Graph()\n",
        "with detection_graph.as_default():\n",
        "  # Init the graph\n",
        "  od_graph_def = tf.GraphDef()\n",
        "  with tf.gfile.GFile(\"/chemin/vers/*.pbb') as fid:\n",
        "    serialized_graph = fid.read()\n",
        "    od_graph_def.ParseFromString(serialized_graph)\n",
        "    tf.import_graph_def(od_graph_def, name='')\n",
        "\n",
        "  # Get all tensors\n",
        "  ops = tf.get_default_graph().get_operations()\n",
        "  all_tensor_names = {output.name for op in ops for output in op.outputs}\n",
        "  tensor_dict = {}\n",
        "  for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:\n",
        "    tensor_name = key + ':0'\n",
        "      if tensor_name in all_tensor_names:\n",
        "        tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)\n",
        "\n",
        "  # detection_masks tensor need ops\n",
        "  detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n",
        "  detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n",
        "  # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n",
        "  real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n",
        "  detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n",
        "  detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n",
        "  detection_masks_reframed =  utils_ops.reframe_box_masks_to_image_masks(\n",
        "detection_masks, detection_boxes, global_height, global_width)\n",
        "  detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n",
        "  # Follow the convention by adding back the batch dimension\n",
        "  tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)\n",
        "\n",
        "  image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "USBUtCurzMbv",
        "colab_type": "text"
      },
      "source": [
        "Let's continue our program with the main method. In this method which is called after the initializations we just presented, we capture the last image of the webcam, we process it, we display the modified image and we start again. So the main method works like this:\n",
        "\n",
        " "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GGYtunLbzflm",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "if __name__ == '__main__':\n",
        "  # Do that here and save a lot of time\n",
        "  with detection_graph.as_default():\n",
        "    with tf.Session(graph=detection_graph) as sess:\n",
        "      while True:\n",
        "        # Get the last frame\n",
        "        frame = cap.read()[1]\n",
        "        # Process last img\n",
        "        new_frame = detect_objects(image_np, sess)\n",
        "        # Display the resulting frame\n",
        "        cv2.imshow('new_frame', new_frame)\n",
        "        if cv2.waitKey(1) & 0xFF == ord('q'):\n",
        "          break"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wvcjTFG1ziiF",
        "colab_type": "text"
      },
      "source": [
        "And so the core of the program is in the detect_objects() method which takes as arguments the image (in NumPy array format) and the Tensorflow session which will allow us to run our model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6wVWXWvCztXn",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def detect_objects(image_np, sess):\n",
        "  # Run inference\n",
        "  output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image_np, 0)})\n",
        "\n",
        "  # all outputs are float32 numpy arrays, so convert types as appropriate\n",
        "  output_dict['num_detections'] = int(output_dict['num_detections'][0])\n",
        "  output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)\n",
        "  output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n",
        "  output_dict['detection_scores'] = output_dict['detection_scores'][0]\n",
        "  output_dict['detection_masks'] = output_dict['detection_masks'][0]\n",
        "\n",
        "  # Display boxes and color pixels\n",
        "  vis_util.visualize_boxes_and_labels_on_image_array(\n",
        "    image_np,\n",
        "    output_dict['detection_boxes'],\n",
        "    output_dict['detection_classes'],\n",
        "    output_dict['detection_scores'],\n",
        "    category_index,\n",
        "    instance_masks=output_dict.get('detection_masks    use_normalized_coordinates=True)\n",
        "\n",
        "  return image_np"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}